<template>
  <div class="mobile-content">
    <Sticky>
      <Search
        v-model.trim="searchForm.keyword"
        show-action
        placeholder="请输入搜索关键词"
        @search="onRefresh"
        @cancel="onRefresh"
      />
      <DropdownMenu>
        <DropdownItem v-model="pagination.sortOrder" :options="orderOptions" @change="onRefresh" />
        <DropdownItem title="筛选" ref="dItem">
          <Cell center title="未推送">
            <template #right-icon>
              <Switch v-model="searchForm['status[]']" active-value="unlink" inactive-value="" />
            </template>
          </Cell>
          <Cell center title="未链接" :border="false">
            <template #right-icon>
              <Switch v-model="searchForm['linkDir[]']" active-value="no" inactive-value="" />
            </template>
          </Cell>
          <div style="padding: 5px 16px;">
            <Button type="primary" block round @click="()=>{dItem.toggle();onRefresh()}">
              确 认
            </Button>
          </div>
        </DropdownItem>
      </DropdownMenu>
    </Sticky>
    <PullRefresh v-model="refreshing" @refresh="onRefresh">
      <List
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多了"
        v-model:error="error"
        :error-text="errorText"
        @load="onLoad"
      >
        <Cell v-for="(item, index) in list" :key="item.id" clickable @click="rowOp(item)">
          <template #title>
            <div class="row-title">
              <span>{{ index + 1 }}.{{ item.name?item.name:item.btname }}</span>
            </div>
          </template>
          <template #label>
            <p>{{ CommonUtil.formatTimestamp(item.addtime) }}</p>
            <Space>
            <Tag type="primary">{{ optionName(item.siteid, siteOptions) }}</Tag>
            <Tag type="primary">{{ optionName(item.categoryid, categoryOptions) }}</Tag>
            <Tag type="primary">{{ optionName(item.clientid, clientOptions) }}</Tag>
            <Tag :plain="item.status!=='linked'" type="primary">{{ item.status==='unlink'?'未推送':(item.status==='linked'?'已推送':'推送中') }}</Tag>
            <Tag :plain="!item.linkDir" type="primary">{{ item.linkDir?'已链接':'未链接' }}</Tag>
            </Space>
          </template>
        </Cell> 
      </List>
    </PullRefresh>
    <ActionSheet v-model:show="opShow" :actions="actions" cancel-text="取消" @select="rowSelect" />

    <div class="menu-btn">
      <Popover  v-model:show="menuShow" :actions="menuActions" placement="left-end" @select="menuSelect">
        <template #reference>
          <Button  round plain icon="bars" type="primary"></Button>
        </template>
      </Popover>
    </div>

    <ActionSheet 
      v-model:show="addShow" 
      title="添加种子"
    >
      <AddTorrent @close="()=>{addShow=false;onRefresh();}"/>
    </ActionSheet>
  </div>
</template>
<!-- <script>
  // 定义组件名称用于keep-alive
  // 使用keep-alive往往是需要name的，解决这个问题通常是通过写两个script标签来解决，一个使用setup，一个不使用
  // 插件vite-plugin-vue-setup-extend可以让我们更优雅的解决这个问题，不用写两个script标签，可以直接在script标签上定义name
  export default {
     name:'torrent-mobile'
  }
 </script> -->
<script name="torrent-mobile" setup>
  import { Sticky, Search, DropdownMenu, DropdownItem, Switch, PullRefresh, List, Cell, Space, Tag, ActionSheet, Button, Popover, Dialog, Notify } from 'vant';
  import { reactive, ref } from 'vue';
  import { useRouter } from 'vue-router';

  import AddTorrent from '@/mobile/Torrent/Add.vue';

  import BaseApi from '@/api/api.js'
  import TorrentApi from '@/api/TorrentApi.js'
  import CommonUtil from '@/utils/CommonUtil.js'

  import store from '@/store';

  const router = useRouter();
  
  const module = 'torrent';
  const list = ref([]);
  const loading = ref(false);
  const finished = ref(false);
  const refreshing = ref(false);
  const error = ref(false);
  const errorText = ref('加载失败，请刷新重试');
  const searchForm = reactive({
    keyword: '',
    'status[]': '',
    'linkDir[]': '',
  });
  const pagination = {
    current: 1,
    pageSize: 20,
    sortField: 'addtime', 
    sortOrder: 'descend' 
  };

  const orderOptions = [
    { text: '默认排序', value: 'descend' },
    { text: '时间正序', value: 'ascend' },
  ];
  const dItem = ref(null);

  const siteOptions = store.state.siteOptions;
  const categoryOptions = store.state.categoryOptions;
  const clientOptions = store.state.clientOptions;
  const libraryOptions = store.state.libraryOptions;

  const optionName = (id, options) => {
    return options.find(item => item.id === id)?.name
  }

  const onLoad = () => {
    BaseApi.list(module, { ...searchForm, ...pagination }).then(response=>{
      if (response.data.code === 1) {
        response.data.data.rows.forEach(item => {
          list.value.push(item);
        });
        
        pagination.current += 1;
        
        if (list.value.length >= response.data.data.total) {
          finished.value = true;
        }
      } else {
        error.value = true;
        errorText.value = `数据加载失败：${response.data.message}`;
      }
    }).catch((error)=>{
        error.value = true;
      errorText.value = `数据加载失败：${error.message}`;
    }).then(()=>{
      loading.value = false;
    })
  };

  const onRefresh = () => {
    refreshing.value = false;
    
    // 清空列表数据
    pagination.current = 1;
    list.value = [];
    finished.value = false;

    error.value = false;
    errorText.value = '';
    // 重新加载数据
    // 将 loading 设置为 true，表示处于加载状态
    loading.value = true;

    onLoad();
  };

  //
  const addShow = ref(false); 
  const menuShow = ref(false);
  const menuActions = [
    { text: '添加' },
    { text: '自动链接' },
  ];
  const menuSelect = (action, index) => {
    if (index === 0) {
      addShow.value = true;
    } else if (index === 1) {
      autoLink();
    }
  };

  const autoLink = () => {
    TorrentApi.autoLink().then(response=>{
      if (response.data.code === 1) {
        Notify({ type: 'success', message: '自动链接开始' });
      } else {
        Notify({ type: 'error', message: `自动链接失败：${response.data.message}` });
      }
    }).catch((error)=>{
      Notify({ type: 'error', message: `自动链接失败：${error.message}` });
    })
  }

  //
  let opRow = undefined;
  const oping = ref(false);
  const opShow = ref(false);
  const actions = [
    { name: '查看' },
    { name: '编辑' },
    { name: '删除', color: '#ee0a24' },
  ];
  const rowOp = (item) => {
    opRow = item;
    opShow.value = true;
  };
  const rowSelect = (item, index) => {
    // 默认情况下点击选项时不会自动收起
    if (index === 0) {
      opShow.value = false;
      router.push({ path: '/m/torrent/detail', query: { id: opRow.id } });
    } else if (index === 1) {

    } else if (index === 2) {
      removeForm.id = opRow.id;
      Dialog.confirm({
        title: '确认删除',
        message:
          '移动端仅删除系统记录,不影响下载器',
        beforeClose: toRemove,
      });
    }
  };

  const removeForm = {
    id: '',
    remove: true, // 从系统删除
    del: false, // 从下载器删除
    delFile: false, // 从磁盘删除
  };

  const toRemove = (action) =>
  new Promise((resolve) => {
    if (action === 'confirm') {
      TorrentApi.removeTorrent(removeForm).then(response=>{
        if (response.data.code === 1) {
          opShow.value = false;
          onRefresh();
          Notify({ type: 'success', message: '删除成功' });
        } else {
          Notify({ type: 'error', message: `删除失败：${response.data.message}` });
        }
      }).catch((error)=>{
        Notify({ type: 'error', message: `删除失败：${error.message}` });
      }).then(()=>{
        resolve(true);
      })
    } else {
      resolve(true);
    }
  });

  // init functions
  
</script>
<style scoped>
.row-title {
}
.label-time {
  margin: 0;
  padding: 0;
}
.menu-btn {
  position: fixed;
  bottom: 20px;
  /* right: 20px; */
  width: 100%;
  text-align: right;
  padding-right: 20px;
}
</style>